package tw.com.diray;

import tw.com.diary.api.domain.SearchResultDTO;
import tw.com.diary.api.service.SearchResultService;
import tw.com.diary.core.SearchResultServiceImpl;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class SearchResultActivity extends Activity {

	private TextView txtQuery;

	private SearchResultDTO dto = new SearchResultDTO();

	private SearchResultService service = new SearchResultServiceImpl();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_result);

		this.getActionBar().setDisplayHomeAsUpEnabled(true);

		this.txtQuery = (TextView) this.findViewById(R.id.queryStatus);

		final ListView queryList = (ListView) this.findViewById(R.id.listView1);

		queryList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent it = new Intent(SearchResultActivity.this,
						DariyView.class);

				Bundle bulde = new Bundle();
				bulde.putString("uuid", dto.getResults().get(position)
						.getUuid());
				it.putExtras(bulde);

				SearchResultActivity.this.startActivity(it);

			}
		});

		handleIntent(getIntent());

	}

	private void handleIntent(Intent intent) {

		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

			final String query = intent.getStringExtra(SearchManager.QUERY);

			this.dto.setQueryText(query);

			this.service.queryByText(dto, this);

			/**
			 * Use this query to display search results like 1. Getting the data
			 * from SQLite and showing in listview 2. Making webrequest and
			 * displaying the data For now we just display the query only
			 */

			txtQuery.setText("查詢結果：" + dto.getResults().size());
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		handleIntent(intent);
	}

}
